package org.qq.controller;

import com.google.common.collect.Lists;
import io.github.melin.sqlflow.analyzer.Analysis;
import io.github.melin.sqlflow.analyzer.StatementAnalyzer;
import io.github.melin.sqlflow.metadata.SchemaTable;
import io.github.melin.sqlflow.parser.SqlFlowParser;
import io.github.melin.sqlflow.tree.statement.EmptyStatement;
import io.github.melin.sqlflow.tree.statement.Statement;
import io.github.melin.superior.common.relational.create.CreateTable;
import io.github.melin.superior.common.relational.create.CreateTableAsSelect;
import io.github.melin.superior.common.relational.dml.InsertTable;
import io.github.melin.superior.common.relational.dml.MergeTable;
import io.github.melin.superior.parser.spark.SparkSqlHelper;
import org.apache.commons.lang3.StringUtils;
import org.qq.service.LineageService;
import org.qq.service.metadata.JdbcQueryMetadataService;
import org.qq.util.FileUtils;
import org.qq.util.SQLLineageMerger;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.io.IOException;

import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.Collections.emptyMap;

@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class LineageController {

    private final LineageService lineageService;

    public LineageController(LineageService lineageService) {
        this.lineageService = lineageService;
    }

    @GetMapping("/dbType")
    public List<String> getSupportedDatabases() {
        return lineageService.getSupportedDatabases();
    }

    @PostMapping("/lineage/analyze")
    public ResponseEntity<Object> analyzeSqlLineage(@RequestBody Map<String, String> requestParams) {
        String dbType = requestParams.get("dbType");
        String querySql = requestParams.get("querySql");
        String columnName = requestParams.get("columnName");
        String isCreateTable = requestParams.get("isCreateTable");
//                System.out.println("请求参数：" + dbType + ",\n" +
//                " ================================ \n" + querySql);
        String result = lineageService.analyzeSqlLineage(dbType,isCreateTable, columnName, querySql);
//        String result = FileUtils.readClasspathFileSafely("data.json").trim();
        return ResponseEntity.ok().body(result);
    }

    @PostMapping("/getLineageData")
    public ResponseEntity<Object> getLineageData(@RequestBody Map<String, String> requestParams) throws IOException {
//        String dbType = requestParams.get("dbType");
//        String querySql = requestParams.get("querySql");
//        System.out.println("请求参数：" + dbType + ",\n" +
//                " ================================ \n" + querySql);
        String result = FileUtils.readClasspathFileSafely("data.json").trim();
        return ResponseEntity.ok().body(result);

    }

    @PostMapping("/getLineageData2")
    public ResponseEntity<Object> getLineageData2(@RequestBody Map<String, String> requestParams) throws IOException {
        String dbType = requestParams.get("dbType");
        String querySql = requestParams.get("querySql");
//        System.out.println("请求参数：" + dbType + ",\n" +
//                " ================================ \n" + querySql);

        // sqlflow 只支持 insert as select 语句血缘解析，create table语句需要先解析出元数据信息
        JdbcQueryMetadataService metadataService = new JdbcQueryMetadataService();
        final List<io.github.melin.superior.common.relational.Statement> statements = SparkSqlHelper.parseMultiStatement(querySql);
        List<SchemaTable> tables = Lists.newArrayList();
        List<String> sqlList=Lists.newArrayList();

        for (io.github.melin.superior.common.relational.Statement statement : statements) {
            if (statement instanceof CreateTable) {
                CreateTable createTable = (CreateTable) statement;
                List<String> columns = createTable.getColumnRels().stream()
                        .map(column -> column.getColumnName())
                        .collect(Collectors.toList());
                SchemaTable table = new SchemaTable(
                        createTable.getTableId().getCatalogName(),
                        createTable.getTableId().getSchemaName(),
                        createTable.getTableId().getTableName(),
                        columns
                );
                tables.add(table);
            }
            if(statement instanceof InsertTable
                    || statement instanceof CreateTableAsSelect
                    ||statement instanceof MergeTable){
                if(StringUtils.isNotBlank(statement.getSql())){
                    sqlList.add(statement.getSql());
                }
            }
        }
        metadataService.addTableMetadata(tables);

        SqlFlowParser SQL_PARSER = new SqlFlowParser();
        // 使用新方法解析多个SQL语句
        List<Statement> multipleStatement = SQL_PARSER.createStatements(sqlList);

        // 创建StatementAnalyzer实例
        StatementAnalyzer statementAnalyzer = new StatementAnalyzer(
                new Analysis(new EmptyStatement(), emptyMap()), // 创建一个临时Analysis对象
                metadataService,
                SQL_PARSER
        );

        // 使用analyzeMultiple方法处理多个语句
        List<String> lineageStr = statementAnalyzer.analyzeMultiple(multipleStatement, Optional.empty());
        // 处理分析结果
        String result = SQLLineageMerger.mergeSQLLineage(lineageStr,null);
        return ResponseEntity.ok().body(result);
    }
}